package com.tgy.Filter;

import com.tgy.utils.Constant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * @ClassName: SysFilter
 * @Description: 注销后禁止直接访问
 * @Auther: 送一一块二向箔
 * @Date: 11:36 2021/12/9
 * @version : V1.0
 */
//@WebFilter(filterName = "sysFilter",urlPatterns = {"/pages/*"}) //这个就相当于在web.xml里面配置
//@ServletComponentScan("com.ai.aaa.aaaa") 加在主启动类
public class SysFilter implements Filter {
    private String ignoreString = null;
    private String uri = null;
    private String url = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //这里获取忽略列表
        ignoreString = filterConfig.getInitParameter("ignore");
        uri = filterConfig.getInitParameter("redirectUri");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        url = httpRequest.getScheme() + "://" + httpRequest.getServerName() + ":" + httpRequest.getServerPort()+uri;
        System.out.println("重定向地址是"+url);

        System.out.println("过滤开始"+ignoreString);
        if(httpRequest.getRequestURI().contains("Login.jsp")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if (httpRequest.getSession().getAttribute(Constant.USER_SESSION)==null) {
            System.out.println("访问地址是"+httpRequest.getRequestURI());
            httpResponse.sendRedirect(url);
            System.out.println("过滤中");
            return;
        }
        System.out.println(httpRequest.getSession().getAttribute(Constant.USER_SESSION));
        //放行一定要写这句
        filterChain.doFilter(servletRequest,servletResponse);


    }

    @Override
    public void destroy() {

    }
}
